//
//  XTHomeTableViewController.swift
//  HrenryWeibo
//
//  Created by 熊涛 on 16/5/11.
//  Copyright © 2016年 熊涛. All rights reserved.
//

import UIKit
import SVProgressHUD
import SVPullToRefresh

//cell唯一标识
let identifier = "cell"
//下拉刷新提示的label的高度
let tipLabelHeight : CGFloat = 44

class XTHomeTableViewController: XTBaseTableViewController {
    //MARK: - 属性
    var statuses : [XTStatus]? {
        didSet {
            //数据模型改变,刷新页面
            tableView.reloadData()
            
        }
    }

    ///判断是否登录
    var login = XTUserAccountViewModel.sharedInstance.isLogin
    
    override func viewDidLoad() {
        super.viewDidLoad()

        if login != true {
            return
        }
        //设置item
        setUpItem()
        
        //设置UI
        prepareUI()
        
        //程序一进来就刷新
        setPullToRefresh()
        
        //添加到navigationBar中
        self.navigationController?.navigationBar.insertSubview(pullDownCountLabel, atIndex: 0)
        
    }
    
    ///设置下拉刷新
    func setPullToRefresh() {
    
        //添加下拉刷新控件到tableview
        tableView.addSubview(pullDownToRefreshView)
        
        //设置下拉刷新的闭包回调
        pullDownToRefreshView.callBack = {
            self.loadNewStatus()
        }
        
        //程序一进来就刷新
        pullDownToRefreshView.beginRefreshing()
        
    }
    
    
    
    //MARK: - 下拉刷新数据
    func loadNewStatus() {
        let since = self.statuses?.first?.id ?? 0
        
        XTStatusViewModel.sharedinstance.loadStatus(since, max_id: 0, callBack: { (status, error) -> () in
            
            //关闭下拉刷新动画
            self.pullDownToRefreshView.endAinmation()
            
            //判断错误
            if error != nil {
                SVProgressHUD.showErrorWithStatus("没有加载微博数据,网络不给力!!!")
                XTPrint(items: "返回数据有错误: \(error)")
                return
            }
            
            //获得多少数据
            let count = status?.count ?? 0
            
            //只有当since > 0 才是刷新更多数据 不是第一次
            //只有是下拉刷新才显示
            if since > 0 {
                self.showPullLabel(count)
            }
            
            //没有获得数据
            if count == 0 {
                SVProgressHUD.showInfoWithStatus("没有获得微博数据")
                return
            }
            
            //下拉获得数据
            if since == 0 {
                self.statuses = status
                XTPrint(items: "下拉刷新获得最新20条数据")
                //将下拉刷新第一次加载数据后添加
                //上拉加载
                self.tableView.addInfiniteScrollingWithActionHandler { () -> Void in
                    XTPrint(items: "上拉加载")
                    self.loadMoreStatus()
                }
            }else {
                self.statuses = status! + self.statuses!
                XTPrint(items: "获得新的数据")
            }
            
        })
        

        
    }
    
    
    //MARK: - 上拉加载
    func loadMoreStatus() {
    
        let max_id = self.statuses?.last?.id ?? 0
        
        XTStatusViewModel.sharedinstance.loadStatus(0, max_id: max_id) { (status, error) -> () in
            
            //数据是否加载错误
            if error != nil {
                SVProgressHUD.showInfoWithStatus("网络不给力,加载数据失败...")
                return
            }
            
            
            let count = status?.count ?? 0
            //是否加载新的微博
            if count == 0 {
                SVProgressHUD.showInfoWithStatus("没有加载到微博数据")
                return
            }
            
            //加载微博
            self.statuses = self.statuses! + status!
            
            //上拉动画停止
           self.tableView.infiniteScrollingView.stopAnimating()
            
        }
        
    }
    
    //MARK: - 弹出下拉刷新的label窗口
    private func showPullLabel(count : Int) {
    
        //label的内容
        let text = count == 0 ? "没有新的微博" : "加载了\(count)条微博"
        pullDownCountLabel.text = text
        
        //当动画还没有回去的时候,又有指定动画出现叠加
        //在做动画之前,将之前的动画移除
        //UIView动画最终也是核心动画
        
        //获取在layer上所有的核心动画
        let animate = self.pullDownCountLabel.layer.animationKeys()
        
        //!=nil 表示还有动画 那么久移除label上的动画 在去之前下一个动画
        if animate != nil {
            
            self.pullDownCountLabel.layer.removeAllAnimations()
        }
        
        //动画的时间
        let duration = 0.75
        
        UIView.animateWithDuration(duration, animations: { () -> Void in
            self.pullDownCountLabel.frame.origin.y = tipLabelHeight
            }) { (_) -> Void in
                UIView.animateWithDuration(duration, delay: 1, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                    self.pullDownCountLabel.frame.origin.y = -tipLabelHeight - 20
                    }, completion: nil)}
    }
    
    //MARK: - 添加控件,设置UI
    func prepareUI () {
    
        //预估cell的行高
        tableView.estimatedRowHeight = 200
        //根据cell的约束,自动计算行高,测量contentview的高度
        tableView.rowHeight = UITableViewAutomaticDimension
        //注册cell
        tableView.registerClass(XTStatusCellCell.self, forCellReuseIdentifier: identifier)
        
    }
    
    //设置item
    func setUpItem() {
    
        //方案三
        //左
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", target: self, selector: "leftBtnClick")
        //右
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, selector: "rightBtnClick")
        
        
        
        //设置中间titleitem
        let name = XTUserAccountViewModel.sharedInstance.userAccount?.screen_name ?? "无名"
        let button = XTItemTitleView(type: UIButtonType.Custom)
        button.setTitle(name  , forState: UIControlState.Normal)
        button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        button.setImage(UIImage(named: "navigationbar_arrow_down"), forState: UIControlState.Normal)
        button.sizeToFit()
        //添加事件
        button.addTarget(self, action: "titleBtnClick:", forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = button
        
        
    }
    
    

    //MARK: - item点击事件
    //左右item
    func leftBtnClick() {
        XTPrint(items: "点击了左边的人头")
    }
    func rightBtnClick() {
        XTPrint(items: "点击了右边的二维码")
    }
    
    //中间item
    func titleBtnClick(button : UIButton) {
        button.selected = !button.selected
        
        if button.selected == true {
            
            UIView.animateWithDuration(0.5, animations: { () -> Void in
                button.imageView?.transform = CGAffineTransformMakeRotation(CGFloat(M_PI-0.01))
            })
            
        }else {
        
            UIView.animateWithDuration(0.5, animations: { () -> Void in
                button.imageView?.transform = CGAffineTransformIdentity
            })
        }
        
    }
    
    //MARK: - 懒加载
    
    //下拉刷新
    private lazy var pullDownToRefreshView : XTPullDownToRefreshControl = XTPullDownToRefreshControl()
    
    //显示刷新数据的数量
    private lazy var pullDownCountLabel : UILabel = {
        let label = UILabel()
        
        //设置属性
        label.font = UIFont.systemFontOfSize(15)
        label.textColor = UIColor.whiteColor()
        label.textAlignment = NSTextAlignment.Center
        label.backgroundColor = UIColor.orangeColor()
        
        //设置frame
        label.frame = CGRect(x: 0, y: -tipLabelHeight - 20, width: UIScreen.mainScreen().bounds.width, height: tipLabelHeight)
        
        
        return label
    }()
    
}


//拓展  实行tableview的数据源方法
extension XTHomeTableViewController {

    
    //MARK: - 数据源方法
    //行
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.statuses?.count ?? 0
        //        return 0
    }
    
    //cell
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //根据identifier去缓存池中找,缓存池中有就返回一个cell,缓存池中没有,就使用注册的cell类型来创建cell
        let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as! XTStatusCellCell
        //        cell.backgroundColor = UIColor.redColor()
        //        cell.imageView?.image = UIImage(named: "info@3x")
        
        //获取模型
        let status = statuses![indexPath.row]
        cell.status = status
        
        return cell
    }
    
}




